#include <assert.h>
#include <stddef.h>
#include <string.h>
#include <time.h>
#include "typedef.h"
#include "common.h"

static void arrayjoin(char* to, const char* from, int length);
static void ltrim(char *s);
static void rtrim(char *s);

void arraycopy(char* dest, int despos, const char* src, int srcpos, int length)
{
	assert(dest);
	assert(src);
	assert(dest >= 0);
	assert(srcpos >= 0);

	arrayjoin(dest + despos, src + srcpos, length);
}

void arrayjoin(char* to, const char* from, int count)
{
	if (from > to)
	{
		char *end = (char*)(from + count);
		while (from < end)
			*(to++) = *(from++);
	}
	else if (from < to)
	{
		char *end = (char*)(from);
		from += count - 1;
		to   += count - 1;
		while (from >= end)
			*(to--) = *(from--);
	}
}

char* trim(char *s)
{
	assert(s);

    ltrim(s);
    rtrim(s);

    return s;
}

void ltrim(char *s)
{
	char *p;
	p = s;
	while(*p == ' ' || *p == '\t'){
	  p++;
	}

	strcpy(s,p);
}

void rtrim(char *s)
{
	int i;
	i = strlen(s)-1;
	while((s[i] == ' ' || s[i] == '\t') && i >= 0){i--;};
	s[i+1] = '\0';
}

char* getdirpath(char* filepath)
{
	char* p = filepath + strlen(filepath);
	while(p != filepath)
	{
		if (*p == '\\' || *p == '/')
		{
			*p = '\0';
			break;
		}
		p--;
	}
	return filepath;
}

char* sprit(const char* src, char delim, char* lbuf, char* rbuf)
{
  	if (src == NULL || *src == '\0')
  		return NULL;

	if (lbuf == NULL || rbuf == NULL)
  		return NULL;

	while(*src != '\0')
  	{
  		if (*src == delim)
  		{
  			src++;
			break;
		}

		*lbuf++ = *src++;
	}
	*lbuf = '\0';

	while(*src != '\0')
  	{
  		*rbuf++ = *src++;
	}

	*rbuf = '\0';

	return lbuf;
}


/*
 * Get the local time and translate it to string.
 */
void getlocaltime(char* buffer, int buflen, const char* format)
{
	time_t rawtime;
	struct tm* timeinfo;

	time( &rawtime );
	timeinfo = localtime( &rawtime );

	strftime( buffer,
			  buflen,
			  format,
			  timeinfo
			  );
}


